import httpclient

"""Kizashi API client demo
Kizashi API http://blog.kizasi.jp/kizasi/66
"""

def kanren(word, span='24'):
    return _request({
        'kw_expr': word,
        'span':    span,
        'type':    'coll',
    })

def kwic(word):
    return _request({
        'kw_expr': word,
        'type':    'kwic',
    })

def ranking(span='24'):
    return _request({
        'span':    span,
        'type':    'rank',
    })

_manager = httpclient.ExtensiveBroker()
def _request(params):
    from urllib import urlencode
    baseuri = 'http://kizasi.jp/kizapi.py?'

    if 'kw_expr' in params:
        if isinstance(params['kw_expr'], unicode):
            params['kw_expr'] = params['kw_expr'].encode('utf8')
    if 'span' in params:
        if params['span'] not in SPAN:
            raise

    return _manager.ask(baseuri + urlencode(params))

SPAN = (
    '24',
    '1w',
    '1m',
)

if __name__ == '__main__':
    import sys
    from twisted.internet import reactor
    from twisted.web2 import stream as stream_mod

    def print_(data):
        print data

    d = globals()[sys.argv[1]](*(sys.argv[2:]))
    d.addCallbacks(httpclient.getResponseBody)
    d.addCallback(lambda x: sys.stdout.write(str(x) + '\n'))
    d.addCallback(lambda x: reactor.stop())
    reactor.run()
